import { defineStore } from 'pinia'
import { ref } from 'vue'
import { nanoid } from 'nanoid/non-secure'

export type Anno = { id: string, label_id: string, start_offset: number, end_offset: number, text: string }

export const useAnnoStore = defineStore('anno', ()=>{
  const list = ref<Anno[]>([])
  const undoStack = ref<Anno[][]>([])
  const redoStack = ref<Anno[][]>([])

  function pushHistory(){
    undoStack.value.push(JSON.parse(JSON.stringify(list.value)))
    if(undoStack.value.length > 100) undoStack.value.shift()
    redoStack.value = []
  }

  function addAnnotation(a: Omit<Anno,'id'>){
    pushHistory()
    list.value.push({ id: nanoid(10), ...a })
  }

  function remove(id: string){
    pushHistory()
    list.value = list.value.filter(i=> i.id !== id)
  }

  function undo(){
    const prev = undoStack.value.pop()
    if(!prev) return
    redoStack.value.push(list.value)
    list.value = prev
  }
  function redo(){
    const next = redoStack.value.pop()
    if(!next) return
    undoStack.value.push(list.value)
    list.value = next
  }

  function clearAll(){
    list.value = []
    undoStack.value = []
    redoStack.value = []
  }

  function setList(annotations: Anno[]){
    pushHistory()
    list.value = annotations
  }

  function focus(id: string){
    // TODO: 滚动定位，当前先占位
    console.log('focus', id)
  }

  function renderedSegments(text: string, labelMap: Record<string, { name: string, color?: string|null }>) {
    // 支持嵌套 / 重叠标注的无重复文本分段
    const anns = [...list.value]
      .filter(a => a.start_offset < a.end_offset && a.start_offset >= 0 && a.end_offset <= text.length)
      .sort((a,b)=> a.start_offset - b.start_offset || a.end_offset - b.end_offset)

    if(anns.length === 0) return [{ type: 'text', text }]

    const boundaries = new Set<number>([0, text.length])
    for(const a of anns){
      boundaries.add(a.start_offset)
      boundaries.add(a.end_offset)
    }
  // 对于部分覆盖（例如内层只覆盖中间两个字），仅切分 start/end 还不够，需要所有标注端点
  // 已加入所有端点，但为了防止某些边界遗漏（浮点/重复），这里再去重排序。
  const points = [...boundaries].sort((a,b)=> a-b)
    const segs: any[] = []
    for(let i=0;i<points.length-1;i++){
      const start = points[i]
      const end = points[i+1]
      if(end <= start) continue
      const slice = text.slice(start, end)
      // 找出覆盖该最小区间的所有标注
      const covering = anns.filter(a => a.start_offset <= start && a.end_offset >= end)
      // 若没有任何覆盖，纯文本
      if(covering.length === 0){
        // 合并相邻纯文本
        const last = segs[segs.length-1]
        if(last && last.type==='text') last.text += slice
        else segs.push({ type:'text', text: slice })
      }else{
        // 排序：起点升序 -> 若同起点，长度降序
        covering.sort((a,b)=> a.start_offset - b.start_offset || (b.end_offset-b.start_offset) - (a.end_offset-a.start_offset))
        // 判断是否严格嵌套链（每一层完全包含下一层）
        let nestedChain = true
        for(let k=1;k<covering.length;k++){
          const prev = covering[k-1]
          const cur = covering[k]
          if(!(prev.start_offset <= cur.start_offset && prev.end_offset >= cur.end_offset)){
            nestedChain = false
            break
          }
        }
        if(nestedChain){
          // 使用最内层颜色（链尾）
          const innermost = covering[covering.length-1]
          const color = labelMap[innermost.label_id]?.color || '#ffec99'
          segs.push({
            type:'hl',
            ids: [innermost.id],
            primaryId: innermost.id,
            text: slice,
            colors: [color],
            multi: false
          })
        } else {
          const colors = covering.map(c=> labelMap[c.label_id]?.color || '#ffec99')
          const primary = covering[covering.length-1]
          segs.push({
            type:'hl',
            ids: covering.map(c=>c.id),
            primaryId: primary.id,
            text: slice,
            colors,
            multi: covering.length>1
          })
        }
      }
    }
    return segs
  }

  return { list, addAnnotation, remove, undo, redo, focus, renderedSegments, clearAll, setList }
})
